/*
 <jFreeDrawer>
    Copyright (C) <2011>  <Jesus Hernandez Sevilla>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.


 */
/*
 * Lienzo.java
 *
 * Created on 13 de diciembre de 2007, 10:20
 */

package sm;

import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import java.util.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.geom.*;
import java.awt.GraphicsEnvironment;
import java.awt.Font;

/**
 *
 * @author  djnano
 */
public class Lienzo extends javax.swing.JPanel {
    
    BufferedImage img; //imagen resultado de aplicar efectos
    BufferedImage imgOrig; //imagen original
    VentanaPrincipal vp; //Ventana principal 
    Graphics2D g2dimg; //Graphics de la imagen 
    String texto = null;
   
    //Variables para las figuras
    Point inicio; //Punto de inicio
    Point fin;    //Punto final
    Point pControl; //Punto de control para curvas
    Point pControl2; //Punto de control2 para curvas
    //Figura para pintar
    Shape figura = null;
    Shape preFigura = null;
    Paint paint = null;
    
    /** Creates new form Lienzo */
    public Lienzo(VentanaPrincipal parent) {
        vp = parent;
        initComponents();
    }
    
    public void paint(Graphics g){
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        //pintar la imagen;
        if(img!=null){
            g2d.setBackground(vp.colorFondo);
            g2d.setColor(vp.colorActual);
            g2d.drawImage(img,0,0,this);
            if(preFigura!=null){
                //rendering
                if(vp.rh != null){
                    g2d.setRenderingHints(vp.rh);
                }else{
                    g2d.setRenderingHints(null);
                }
                //ponemos el stroke
                if(vp.sk != null){
                    g2d.setStroke(vp.sk);
                }
                //ponemos el paint
                if(paint != null){
                    g2d.setPaint(paint);
                    g2d.fill(preFigura);
                }
                
                g2d.draw(preFigura);
                
                
            }else if(texto !=null ){//pintar el texto                
                g2d.setFont(vp.font);
                if(vp.sk != null){
                    g2d.setStroke(vp.sk);
                }
                if(paint != null){
                    g2d.setPaint(paint);
                }
                g2d.drawString(texto,inicio.x,inicio.y);
            }
            
        }
    }
    
    public void paintForma(Shape fig){
        //rendering
        if(vp.rh!=null)
            g2dimg.setRenderingHints(vp.rh);
        //strokes
        if(vp.sk!=null)
            g2dimg.setStroke(vp.sk);
        //color
        g2dimg.setColor(vp.colorActual);
        g2dimg.setBackground(vp.colorFondo);
        
        
        if(fig!=null){
            if(paint!=null){
                g2dimg.setPaint(paint);
                g2dimg.fill(fig);
            }
        g2dimg.draw(fig);    
        }
    }
    
    public void paintString(String str, Point p){
        //ponemos el tipo de rendering
        if(vp.rh!=null)
            g2dimg.setRenderingHints(vp.rh);
        //ponemos el stroke
        if(vp.sk!=null)
            g2dimg.setStroke(vp.sk);
        //ponemos el color para pintar
        g2dimg.setColor(vp.colorActual);
        g2dimg.setBackground(vp.colorFondo);
        //seleccionamos la fuente para pintar
        g2dimg.setFont(vp.font);
        if(str!=null){
            g2dimg.drawString(str, p.x, p.y);
        }
        
    }
    //set image
    public void setImageOriginal(BufferedImage img2){
        if(img2!=null){
            this.imgOrig = img2;
            setImage(img2);
        }            
    }
    
    public void setImage(BufferedImage img2){
        if(img2!=null){
            this.img = img2;
            g2dimg = img.createGraphics();
            this.setPreferredSize(new Dimension(img.getWidth(),img.getHeight()));            
        }
    }
    
    //devuelve la imagen
    public BufferedImage getImage(){
        return img;
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {

        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                formMouseDragged(evt);
            }
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                formMouseMoved(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                formKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                formKeyTyped(evt);
            }
        });
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                formMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                formMouseReleased(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void formKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyTyped
// TODO add your handling code here:
        JOptionPane.showMessageDialog(null,texto,"evtTyped",JOptionPane.QUESTION_MESSAGE);
    }//GEN-LAST:event_formKeyTyped

    private void formKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyReleased
// TODO add your handling code here:
        JOptionPane.showMessageDialog(null,texto,"evtReleased",JOptionPane.QUESTION_MESSAGE);
    }//GEN-LAST:event_formKeyReleased

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
// TODO add your handling code here:
            JOptionPane.showMessageDialog(null,texto,"evtPressed",JOptionPane.QUESTION_MESSAGE);
        if(vp.herramientaActual == 7){
            int code = evt.getKeyCode();
            String s = evt.getKeyText(code);
            texto.concat(s);
            JOptionPane.showMessageDialog(null,texto,"e",JOptionPane.QUESTION_MESSAGE);
            this.repaint();
        }
    }//GEN-LAST:event_formKeyPressed

    private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed
// TODO add your handling code here:
        // TODO add your handling code here:
        //mirar la herramienta que tenemos seleccionada en la Ventana Principal
        int herramienta = vp.herramientaActual;
        inicio = evt.getPoint();
        fin = inicio;
        
        //Le decimos a g2dimg las opciones con las que queremos que se pinte en la imagen
        //opciones de pintado
        g2dimg.setColor(vp.colorActual);
        g2dimg.setBackground(vp.colorFondo);
        //fin de opciones de pintado    
        
        //Crear la forma cuando se haga click
        switch(herramienta){
            case 1:
               //crear una linea
                preFigura = new Line2D.Float(inicio,fin);
                break;
            case 2:
                //crear un trazo libre
                int grosor = Integer.parseInt(vp.grosorSpinner.getValue().toString());
                preFigura = new Ellipse2D.Float(inicio.x,inicio.y,grosor,grosor);
                g2dimg.fill(preFigura);
                break;
            case 3:
                //crear un rectangulo
                
                preFigura = new Line2D.Float(inicio,fin).getBounds2D();
                break;
            case 4:
                //crear un rectangulo redondeado
                preFigura = new RoundRectangle2D.Float(inicio.x,inicio.y,1,1,25,25);
                break;
            case 5:
                //crear una ellipse
                preFigura = new Line2D.Float(inicio,fin);
                break;
            case 6:
                break;
            case 7:
                //Crear texto 
                texto = "";
                //Lanzar Dialogo de crear Texto
                //new textoDialog(null, this).setVisible(true);
                break;
        }
        this.repaint();
    }//GEN-LAST:event_formMousePressed

    private void formMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseReleased
// TODO add your handling code here:
        //mirar la herramienta que tenemos seleccionada en la Ventana Principal
        int herramienta = vp.herramientaActual;

        //Terminar la forma y pintarla en la imagen
        switch(herramienta){
            case 1:
                //crear una linea
                paintForma(preFigura);
                break;
            case 2:
                //crear un trazo libre
                paintForma(preFigura);
                break;
            case 3:
                //crear un rectangulo
                paintForma(preFigura);
                break;
            case 4:
                //crear un rectangulo redondeado
                paintForma(preFigura);
                break;
            case 5:
                //crear una elipse
                paintForma(preFigura);
                break;
            case 6:
                break;
            case 7:
                //no se hace nada al soltar el raton con esta herramienta
                break;
        }
        preFigura = null;
        paint = null;
        this.repaint();
    }//GEN-LAST:event_formMouseReleased

    private void formMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseDragged
// TODO add your handling code here:
        //mirar la herramienta que tenemos seleccionada en la Ventana Principal
        boolean crearFill = false;
        int herramienta = vp.herramientaActual;
        fin = evt.getPoint();
        Point x1, x2;
        float maxX, minX, height, widht ;
        Shape aux;

        //Crear la forma cuando se haga click
        switch(herramienta){
            case 1:
               //crear una line
                ((Line2D.Float)preFigura).setLine(inicio.x,inicio.y,fin.x,fin.y);
                break;
            case 2:
                //crear un trazo libre
                int grosor = Integer.parseInt(vp.grosorSpinner.getValue().toString());
                preFigura = new Ellipse2D.Float(fin.x,fin.y,grosor,grosor);
                paintForma(preFigura);
                break;
            case 3:
                //crear un rectangulo
                preFigura = new Line2D.Float(inicio,fin).getBounds2D(); 
                break;
            case 4:
                //crear un rectangulo redondeado
                aux = new Line2D.Float(inicio,fin).getBounds2D();
                x1 = new Point();
                x2 = new Point();
                x1.x = (int)((Rectangle2D.Float)aux).getMinX();
                x1.y = (int)((Rectangle2D.Float)aux).getMinY();
                float w = (float)((Rectangle2D.Float)aux).getWidth();
                float h = (float)((Rectangle2D.Float)aux).getHeight();
                ((RoundRectangle2D)preFigura).setRoundRect(x1.x,x1.y,w,h,25,25); 
                break;
            case 5:
                //crear una elipse
                aux = new Line2D.Float(inicio,fin);
                height = (float)((Line2D.Float)aux).getBounds().getHeight();
                widht = (float)((Line2D.Float)aux).getBounds().getWidth();
                preFigura = new Ellipse2D.Float((float)inicio.x, (float)inicio.y, widht, height);
                break;
            case 6:
                break;
            case 7:
                //Crear texto 
                break;
        }
        if(vp.tipoRelleno >0){
            switch(vp.tipoRelleno){
            case 1: 
                //relleno liso
                paint = new Color(vp.colorFondo.getRGB());
                break;
            case 2: 
                //degradado horizontal
                minX = (float) preFigura.getBounds().getMinX();
                maxX = (float) preFigura.getBounds().getMaxX();     
                paint = new GradientPaint(minX,0, vp.colorActual, maxX,0,vp.colorFondo);
                break;
            case 3: 
                //degradado vertical
                minX = (float) preFigura.getBounds().getMinY();
                maxX = (float) preFigura.getBounds().getMaxY();     
                paint = new GradientPaint(0 ,minX, vp.colorActual, 0, maxX,vp.colorFondo);
                break;
            }
        }
        
        this.repaint();
        //((Graphics2D)this.getGraphics()).draw(preFigura);        
    }//GEN-LAST:event_formMouseDragged

    private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
// TODO add your handling code here:
        vp.labelEstado.setText("{"+evt.getX()+"."+evt.getY()+"}");
    }//GEN-LAST:event_formMouseMoved
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    
}
